package com.zhkj.txg.module.member.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.product.vm.ShareViewModel
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.ShareUtils
import kotlinx.android.synthetic.main.activity_member_share.*

class MemberShareActivity : ViewModelActivity<ShareViewModel>() {

    companion object {
        private val SHARE_URL = "shareUrl"
        fun open(activity: Activity, shareUrl: String) {
            val intent = Intent(activity, MemberShareActivity::class.java).putExtra(SHARE_URL, shareUrl)
            activity.startActivity(intent)
        }
    }

    override val layoutResId: Int = R.layout.activity_member_share
    override fun statusTitleBar(): View? = titleMemberShare
    override fun setViewModel(): ShareViewModel = createViewModel()

    override fun initUI() {
        // 保存图片
        tvShareSaveSingle.setOnClickListener {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, {
                viewModel.saveView2Picture(root, false)
            }, { toast(getString(R.string.read_permission_deny)) })
        }
        // 微信分享
        tvShareWeChat.setOnClickListener {
            ShareUtils.shareUrl2Friends(
                this,
                ConfigManager.getShareTitle() ?: "",
                ConfigManager.getShareContent() ?: "",
                null,
                intent.getStringExtra(SHARE_URL) ?: "",
                true
            )
        }
    }

    override fun initData() {
        ImageUtils.loadCircleImage(this, ivProductPic, AccountManager.getAvatar())
        tvProductTitle.text = AccountManager.getNickname()
        viewModel.getQRCode(0)
    }

    override fun initViewModel() {
        viewModel.qrCodeLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                ImageUtils.loadRoundCornerImage(this, ivProductCode, it.qrCode)
            }
        })
        viewModel.saveViewLiveData.observe(this, Observer {
            toast(getString(R.string.save_picture_success))
        })
    }
}